package com.jianxiu.web;

import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jianxiu.bean.Cons;
import com.jianxiu.bean.Result;
import com.jianxiu.bean.SecUser;
import com.jianxiu.service.SecUserService;
import com.jianxiu.utils.Md5SaltTool;

/**
 * Created by tancw on 2017/3/21.
 */
@Controller
public class HomeController {

    @Autowired
    private SecUserService secUserService;

    private final ResourceLoader resourceLoader;

    @Autowired
    public HomeController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @RequestMapping("/")
    public String index(Model model) {
        return "index";
    }

    @RequestMapping("/home")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping("/tologin")
    public String tologin(Model model) {
        return "signin";
    }

    @RequestMapping("loginout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Cons.SESSION_USER);
        return "signin";
    }

    @RequestMapping("redirect")
    public String toPage(String to) {
        return to;
    }

    @RequestMapping(value = "/upload/{filename:.+}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(Cons.FILE_ROOT, filename).toString()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(HttpServletRequest request, String username, String password) {
        SecUser user = secUserService.getByname(username);
        if (null == user) return Result.byMsg("无此用户,请联系管理员!");
        try {
            if (Md5SaltTool.validPassword(password, user.getPassword())) {
                request.getSession().setAttribute(Cons.SESSION_USER, user);
                request.getSession().setMaxInactiveInterval(1800);
                return Result.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.byMsg("密码错误");
        }
        return Result.byMsg("用户名或密码错误");
    }
}
